/**
 * 详情对话框
 */
var GoodsPicInfoDlg = {
    data: {
        goodsId: "",
        goodsPic: "",
        goodsUrl: "",
        BrandsId: "",
        goodsPics: "",
        goodsDetails: "",
        price:""
    }
};

layui.use(['form', 'admin', 'ax', 'upload', 'layedit'], function () {
    var $ = layui.jquery;
    var $ax = layui.ax;
    var form = layui.form;
    var admin = layui.admin;
    var upload = layui.upload;
    var layedit = layui.layedit;
    var _index=1;
    var newPathList=[];
    //让当前iframe弹层高度适应
    admin.iframeAuto();


    var imgs = "";


    layedit.set({
        uploadImage: {
            url: Feng.ctxPath + '/system/uploads2' //接口url
            , type: 'post' //默认post
        }
    });
    /*富文本*/
    var index =layedit.build('goodsDetails'); //建立编辑器
    //获取详情信息，填充表单
    var ajax = new $ax(Feng.ctxPath + "/goods/detailA?id=" + Feng.getUrlParam("id"));
    var result = ajax.start();
    if (result.data.goodsPic != null && result.data.goodsPic != '') {
        $('#img1').attr('src', result.data.goodsPic);
    }

    if (result.data.goodsPics != null && result.data.goodsPics != '') {
        var html = "";
        imgs = result.data.goodsPics.split(",");
        for (var i = 0; i < imgs.length; i++) {
            if(imgs[i]){
                html = html + '<div id="" class="file-iteme file-iteme-'+i+'">' +
                    '<div class="handle"></div>' +
                    '<img style="width: 30%" src="' + imgs[i] + '" alt="' + imgs[i] + '" class="layui-upload-img">' +
                    '<div class="info">' + '<span class="layui-icon layui-icon-delete shanchu" data-class="file-iteme-'+i+'" data-value="' +imgs[i]+ '"></span>' + '</div>' +
                    '<div><input type="number" name="changeIndex" class="changeIndex" data-index="'+_index+'" data-key="'+_index+'" style="max-width: 70px;margin: 40px auto;" placeholder="请输入对应图片的排序序号"/></div>' +
                    '</div>';
                _index++;
            }
        }

        $("#goodsPics").val(imgs.join(","));

        $('#demo2').append(html);


        $(".shanchu").click(function (e) {
            var img=$(this).attr('data-value')
            var part='.'+$(this).attr('data-class')
            shanchu(img,part)
        })
        $('.changeIndex').each(function (e){
            $(this).val($(this).attr('data-index'))
        })
    }

    $(document).on("change", ".changeIndex", function (event) {
        //现在输入的序号，
        var val=$(this).val();
        console.log(val)
        //原来的序号的序号，
        var valIndex=$(this).attr('data-index');
        console.log(valIndex)
        if(val>$('.changeIndex').length){
            $(this).val($('.changeIndex').length)
        }
        if(val<1){
            $(this).val(1);
        }
        //吧输入的新序号和对应位置序号调换
        $('.changeIndex').each(function (e){
            //如果输入的值和原来的序号对应
            if($(this).attr('data-index')==val){
                $(this).val(valIndex);//对应的序号框改变值
                $(this).attr('data-index',valIndex);//原来的序号的序号也需要改变
                changeIndexPath();
            }
            //
            // if(e+1==val){
            //
            // }
        })
        //改变对应的原来的序号的序号
        $(this).attr('data-index',val);
    });
    var changeIndexPath =function () {
        //获取所有的图片地址；
        var allPath= $("#goodsPics").val().split(',');


        //$('.changeIndex')的下标对应的图片地址的下标；
        $("input[name='changeIndex']").each(function (e){
            var newIndex=parseInt($(this).val())-1;
            var oldPath=parseInt($(this).attr('data-key'))-1;//最初的排列标示
            if(oldPath!=oldPath.length-1){
                newPathList[newIndex]=allPath[oldPath]
            }

        });
        var new_path='';
        newPathList.forEach(function (item,index) {
            new_path+=item+",";
        })
        console.log(newPathList);
        console.log(new_path);
        $("#goodsPics").val(new_path);
    };

    //删除
    window.shanchu = function(i,b){
        $.ajax({
            "url": Feng.ctxPath + "/goodsPic/updateGoodsPic?img=" + i + ",",
            "type": "POST",
            //"date":{"img":i} ,
            "dataType": "JSON",
            "success": coolBack
        });
        <!--获取回调函数-->
        function coolBack() {
            Feng.success("删除数据成功！");
            //window.location.reload();

            $(b).remove()
            var pathImg=$("#goodsPics").val().split(',');
            var newPath='';
            for (var j=0;j<pathImg.length;j++){
                if(pathImg[j]&& pathImg[j]!=i){
                    newPath+=pathImg[j]+","
                }
            }
            $("#goodsPics").val(newPath);

        }
    }







    if (result.data.BrandsId != null) {
        BrandsId = result.data.BrandsId;
    }
    $("#price").val(result.data.price);
    $("#goodsId").val(result.data.goodsId);
    $("#pictureInputHidden").val(result.data.goodsPic);
    /* form.val('goodsPicForm', result.data);*/
    //表单提交事件

    form.on('submit(btnSubmit)', function (data) {
        var ajax = new $ax(Feng.ctxPath + "/goodsPic/addItem", function (data) {
            Feng.success("更新成功！");
            window.location.href = Feng.ctxPath + '/goods'
        }, function (data) {
            Feng.error("更新失败！" + data.responseJSON.message)
        });
        ajax.set("Details",encode64(layedit.getContent(index)));
        ajax.set(data.field);
        ajax.start();
        return false;
    });

    //返回按钮
    $("#backupPage").click(function () {
        window.location.href = Feng.ctxPath + '/goods'
    });


    upload.render({
        elem: '#picBtn'
        , url: Feng.ctxPath + '/goodsPic/UploadFileUtils'
        , before: function (obj) {
            obj.preview(function (index, file, result) {
                $('#img1').attr('src', result);
            });
        }
        , done: function (res) {
            $("#pictureInputHidden").val(res.data.fileId);
            Feng.success(res.message);
        }
        , error: function () {
            Feng.error("上传图片失败！");
        }
    });
    var filePath1 = '';
    if ($("#goodsPics").val() != null && $("#goodsPics").val() != "") {
        filePath1 = $("#goodsPics").val() + ",";
    } else {
        filePath1 = '';
    }



    //循环的次数
    var cycle = 0;
    var rescycle = 0;

    //执行实例
    upload.render({
        elem: '#bill_pic'
        , url: Feng.ctxPath + '/goodsPic/multipleGraph'
        , multiple: true
        , accept: 'file'
        , before: function (obj) {
            obj.preview(function (index, file, result) {
                cycle ++;

            });
        }
        , done: function (res) {
            //上传完毕 拼接地址
            rescycle++;
            layer.msg(res.message);
            if(rescycle == cycle){
                $("#goodsPics").val($("#goodsPics").val()+res.data);
                res.data=  res.data.split(',')
                for(var i =0;i<res.data.length;i++){
                    if(res.data[i]){
                        $('#demo2').append(
                            '<div id="" class="file-iteme-l-'+i+'">' +
                            '<img style="width: 30%" src="' + res.data[i] + '"  class="layui-upload-img">' +
                            '<div class="handle"><span class="layui-icon layui-icon-delete shanchuSh" data-class="file-iteme-l-'+i+'" data-value="' +res.data[i]+ '"></span></div>' +
                            '<div><input type="number" name="changeIndex" class="changeIndex" data-index="'+_index+'" data-key="'+_index+'" style="max-width: 70px;margin: 40px auto;" placeholder="请输入对应图片的排序序号"/></div>' +
                            '</div>'
                        )
                        _index++;
                        $('.changeIndex').each(function (e){
                            $(this).val($(this).attr('data-index'))
                        })
                    }
                }
//onclick="shanchuSh(\'' + res.data[i] + '\')"
                $(".shanchuSh").click(function (e) {
                    var img=$(this).attr('data-value')
                    var part='.'+$(this).attr('data-class')
                    shanchuSh(img,part)
                })

            }
        },
        error: function (res) {
            layer.msg(res.message);
        }
    });


    //删除
    window.shanchuSh = function(e,b){

        $(b).remove()
        var pathImg=$("#goodsPics").val().split(',');
        var newPath='';
        for (var j=0;j<pathImg.length;j++){
            if(pathImg[j]&& pathImg[j]!=e){
                newPath+=pathImg[j]+","
            }
        }
        $("#goodsPics").val(newPath);
    }




    // 删除图片
    $(document).on("click", "#deleteBillpic", function (event) {
        $("#demo2").html("");
        $("#goodsPics").val("");
    });

});

var keyStr = "ABCDEFGHIJKLMNOP" + "QRSTUVWXYZabcdef" + "ghijklmnopqrstuv"
    + "wxyz0123456789+/" + "=";

function encode64(input) {
    var output = "";
    var chr1, chr2, chr3 = "";
    var enc1, enc2, enc3, enc4 = "";
    var i = 0;
    do {
        chr1 = input.charCodeAt(i++);
        chr2 = input.charCodeAt(i++);
        chr3 = input.charCodeAt(i++);
        enc1 = chr1 >> 2;
        enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
        enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
        enc4 = chr3 & 63;
        if (isNaN(chr2)) {
            enc3 = enc4 = 64;
        } else if (isNaN(chr3)) {
            enc4 = 64;
        }
        output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2)
            + keyStr.charAt(enc3) + keyStr.charAt(enc4);
        chr1 = chr2 = chr3 = "";
        enc1 = enc2 = enc3 = enc4 = "";
    } while (i < input.length);

    return output;
}
